package engine

import (
	m "awesomeProject2/model"
	"sort"
	"sync"
)

type OrderBook struct {
	mu         sync.Mutex
	BuyOrders  []*m.Order
	SellOrders []*m.Order
}

func min(a, b float64) float64 {
	if a < b {
		return a
	}
	return b
}

func (ob *OrderBook) AddOrder(order *m.Order) {
	ob.mu.Lock()
	defer ob.mu.Unlock()
	if order.Type == m.BUY {
		ob.BuyOrders = append(ob.BuyOrders, order)
	} else {
		ob.SellOrders = append(ob.SellOrders, order)
	}
}

func (ob *OrderBook) Sort() {
	sort.Slice(ob.BuyOrders, func(i, j int) bool {
		if ob.BuyOrders[i].Price == ob.BuyOrders[j].Price {
			return ob.BuyOrders[i].CreatedAt.Before(ob.BuyOrders[j].CreatedAt)
		}
		return ob.BuyOrders[i].Price > ob.BuyOrders[j].Price
	})

	sort.Slice(ob.SellOrders, func(i, j int) bool {
		if ob.SellOrders[i].Price == ob.SellOrders[j].Price {
			return ob.SellOrders[i].CreatedAt.Before(ob.SellOrders[j].CreatedAt)
		}
		return ob.SellOrders[i].Price < ob.SellOrders[j].Price
	})

}
